#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试账号创建脚本
用于在智习伴项目中创建标准测试账号
"""

import sqlite3
import bcrypt
import os

def get_db_connection():
    """获取数据库连接"""
    project_root = os.path.join(os.path.dirname(__file__))
    db_path = os.path.join(project_root, 'zhixiban.db')
    conn = sqlite3.connect(db_path)
    conn.row_factory = sqlite3.Row
    return conn

def create_test_users():
    """创建测试账号"""
    conn = get_db_connection()
    cursor = conn.cursor()
    
    # 测试账号信息
    test_users = [
        {
            'username': 'teacher',
            'password': 'teacher123',
            'role': 'teacher',
            'email': 'teacher@zhixiban.com'
        },
        {
            'username': 'student',
            'password': 'student123',
            'role': 'student',
            'email': 'student@zhixiban.com'
        }
    ]
    
    created_users = []
    
    for user_data in test_users:
        # 检查用户是否已存在
        cursor.execute('SELECT * FROM users WHERE username = ?', [user_data['username']])
        existing_user = cursor.fetchone()
        
        if existing_user:
            print(f"用户 {user_data['username']} 已存在，跳过创建")
            created_users.append({
                'username': existing_user['username'],
                'role': existing_user['role'],
                'id': existing_user['id']
            })
            continue
        
        # 密码加密
        hashed_password = bcrypt.hashpw(user_data['password'].encode('utf-8'), bcrypt.gensalt())
        
        # 创建用户
        cursor.execute('''
            INSERT INTO users (username, password, role, email)
            VALUES (?, ?, ?, ?)
        ''', [user_data['username'], hashed_password, user_data['role'], user_data['email']])
        
        user_id = cursor.lastrowid
        created_users.append({
            'username': user_data['username'],
            'role': user_data['role'],
            'id': user_id
        })
        print(f"成功创建用户: {user_data['username']} (ID: {user_id}, 角色: {user_data['role']})")
    
    conn.commit()
    conn.close()
    
    # 打印测试账号信息
    print("\n" + "=" * 50)
    print("测试账号信息:")
    print("=" * 50)
    for user in created_users:
        print(f"用户名: {user['username']:<10} | 角色: {user['role']:<7} | ID: {user['id']}")
    print("=" * 50)
    print("默认密码:")
    print("  教师账号: teacher / teacher123")
    print("  学生账号: student / student123")
    print("=" * 50)

if __name__ == '__main__':
    print("智习伴测试账号创建工具")
    print("=" * 30)
    create_test_users()